import getUUID from "@/utils/getUUID"
import { message } from "antd"
import dayjs from "dayjs";
import { useRef, useState } from "react"

const combineAll = (skuList: Goods.Sku[]): Goods.GoodsStock[] => {
  let result: Goods.SkuValue[][] = [[]];
  for (let sku of skuList) {
    let temp = [];
    for (let val of sku.values) {
      for (let res of result) {
        temp.push([...res, val]);
      }
    }
    result = temp;
  }
  return result.filter(item => item.length).map((item, index) => {
    const _stockSku: string[] = []
    const _skuName: string[] = []
    item.forEach(item => {
      _stockSku.push(item.fakeId!)
      _skuName.push(item.valueName)
    })
    const _id = dayjs().valueOf()
    return ({
      id: String(_id + index),
      fakeId: _id + index,
      stockNum: 0,
      stockImg: item.find(sku => sku.valueDesc)?.valueDesc,
      stockName: _skuName.join('-'),
      stockSku: _stockSku,
      stockPrice: 0,
      stockLinePrice: 0,
      skuName: _skuName.join('-'),
      weight: 0,
    })
  });
}

const useGoodsState = () => {
  const [skuList, setSkuList] = useState<Goods.Sku[]>([])
  const [goodsStock, setGoodsStock] = useState<Goods.GoodsStock[]>([])

  const generateGoodsStock = (value: Goods.Sku[]) => {
    setSkuList(value)
    const newGoodsStock = combineAll(value.filter(it => it.values.length))
    setGoodsStock(newGoodsStock.map(item => {
      const skuNames = item.skuName?.split('-')
      const old = goodsStock.find(oldItem => {
        const oldSkuNames = oldItem.skuName?.split('-')
        return skuNames?.length === oldSkuNames?.length && oldSkuNames?.every(_sku => skuNames?.includes(_sku))
      })
      if (old) return old
      return item
    }))
  }

  return {
    skuList, setSkuList,
    goodsStock, setGoodsStock,
    generateGoodsStock,
  }
}

export default useGoodsState